<?php
namespace Api\Controller;
use Think\Controller;

class IndexController extends Controller {


    /**
     * 分类列表
     */
    public function cats(){
        $lists = M('categories')->where('is_show = 1')->order('sort_order asc')->field('id,cat_name')->select();
        jsonReturn(array('data' => $lists));
    }

    /**
     * 赏金列表
     */
    public function bouns(){
        $lists = $this->getBonusConfig();
        jsonReturn(array('data' => $lists));
    }

    /**
     * 悬赏列表
     */
    public function rewards(){
        $lists = $this->getRewardConfig();
        jsonReturn(array('data' => $lists));
    }

    public function getBonusConfig(){
        $find = M('config')
            ->where("inc_type = 'basic' and name='bonus_str'")->getField('value');
        if($find){
            $find = explode(',',$find);
            sort($find);
            return $find;
        }
        return false;
    }

    public function getRewardConfig(){
        $find = M('config')
            ->where("inc_type = 'basic' and name='reward_str'")->getField('value');
        if($find){
            $find = explode(',',$find);
            sort($find);
            return $find;
        }
        return false;
    }

    /**
     * 开始提问的准备参数
     */
    public function init(){
        $rewards = $this->getRewardConfig();
        $cats = M('categories')->where('is_show = 1')->order('sort_order asc')->field('id,cat_name')->select();
        $normal = M('config')
            ->where("inc_type = 'basic' and name='normal_hour' ")->getField('value');
        $speed = M('config')
            ->where("inc_type = 'basic' and name='speed_hour' ")->getField('value');
        $timer = array('normal' => date('Y-m-d H:i' ,time() + ($normal*60*60)) , 'speed' =>  date('Y-m-d H:i' ,time() + ($speed*60*60)) );

        jsonReturn(array(
            'cats' => $cats,
            'rewards' => $rewards,
            'timer' => $timer,
        ));

    }


    public function  aa(){
        $question_id = 88;
        $reg_id =  '190e35f7e07052d0df1';
        $txt = '测试';
        $type = 1;

        Vendor("JPush.JPush");
        $client = new \JPush(xrkCache('jpush.jpush_appkey'),xrkCache('jpush.jpush_master_secret'));
        $result = $client->push()
            ->setPlatform('all')
            ->addRegistrationId($reg_id)
            ->addIosNotification($txt,'default', \JPush::DISABLE_BADGE, true, '',array('id' => $question_id))
           // ->setOptions(null,null,null,false)
            ->send();

        $result = $client->push()
            ->setPlatform('all')
           // ->setOptions(null,null,null,false)
            ->addRegistrationId($reg_id)
            ->addAndroidNotification($txt, '会计问答', 1, array('id' => $question_id))
            ->addIosNotification($txt,'default', \JPush::DISABLE_BADGE, true, '',array('id' => $question_id))
            ->sends();

        print_r($result);die;


    }

    public function bb(){
        $question_id = 88;
        $reg_id =  '1114a897929c08eac37';
        $txt = '测试123';
        $time = "2017-08-26 11:26:00";

        Vendor("JPush.JPush");
        $client = new \JPush(xrkCache('jpush.jpush_appkey'),xrkCache('jpush.jpush_master_secret'));

        $payload = $client->push()
            ->setPlatform("all")
            ->addRegistrationId($reg_id)
            ->addIosNotification($txt,'default', \JPush::DISABLE_BADGE, true, '', array('id' => $question_id))
            ->build();
// 创建一个2016-12-22 13:45:00触发的定时任务
        $response = $client->schedule()->createSingleSchedule("定时任务", $payload, array("time"=>$time));


        $payload = $client->push()
            ->setPlatform("all")
            ->addRegistrationId($reg_id)
            ->addAndroidNotification($txt,'财税答疑', 1,  array('id' => $question_id))
            ->addIosNotification($txt,'default', \JPush::DISABLE_BADGE, true, '',  array('id' => $question_id))
            ->builds();
// 创建一个2016-12-22 13:45:00触发的定时任务
        $response = $client->schedule()->createSingleSchedule("定时任务", $payload, array("time"=>$time));

        print_r($response);die;

    }


    public function check_question(){
        $now = time();
        $select = M('question_answer')->alias('qa')
            ->join('left join __QUESTION__ as q on q.id = qa.question_id')
            ->field('qa.id,qa.question_id,qa.answer_id,q.user_id')
            ->where("q.answer_status = 1 and question_status != 1 and ".$now." > q.stop_time")
            ->select();
        if(!$select){
            return;
        }
        $answer_id = xrkCache('basic.accountant_head');
        if(!$answer_id){
            return;
        }
        $reg_id = M('accountant_users')->where('au_id = '.$answer_id)->getField('registered_id');

        $q = $qa = $reset = array();
        foreach ($select as $val){
            if($val['user_id'] > 0) { //判断left join 问题记录是否存在
                //$q[] = array('id' => $val['question_id'], 'stop_time' => time() + (5 * 24 * 60 * 60));
               // $qa[] = array('id' => $val['id'], 'answer_id' => $answer_id , 'update_time' => time());
                $q[] = $val['question_id'];
                $qa[] = $val['id'];
                $reset[] = array('au_id' => $val['answer_id'] , 'question_id' => $val['question_id'] , 'user_id' => $val['user_id'] , 'type' => 0 , 'status' => 1);
            }
        }

        //M('question')->addAll($q);
        //M('question_answer')->addAll($qa);
        if($q){
            M()->query( "update ".C('DB_PREFIX')."question set stop_time = '".(time() + (5 * 24 * 60 * 60))."'  where id in  (".implode(',' , $q).")" );
            foreach ($q as $id){
                $this->schedule_jpush($id,$reg_id);
            }
        }
        if($qa){
            M()->query(
                "update ".C('DB_PREFIX')."question_answer 
                set answer_id = ".$answer_id." , update_time = ".time()."
                where id in  (".implode(',',$qa).")");
        }
        //还原悬赏的金额给固定回答者
        foreach ($reset as $where) {
            M('pay_log')->where($where)->save(array('au_id' => $answer_id));
        }
    }

    /***
     * @param $question_id
     * @param $reg_id
     * @param int $type
     * 定时推送
     */
    public function schedule_jpush($question_id,$reg_id,$type = 2){
        /*$question_id = 88;
        $reg_id =  '1114a897929c08eac37';
        $txt = '测试123';*/
        if(!$question_id || !$reg_id){
            return;
        }
        $time = date('Y-m-d')." 09:00:00";
        if(time() > strtotime($time)){
            return;
        }
        $txt = '您收到了一条问题，赶快去回复吧！';

        Vendor("JPush.JPush");
        $client = new \JPush(xrkCache('jpush.jpush_appkey'),xrkCache('jpush.jpush_master_secret'));

        $payload = $client->push()
            ->setPlatform("all")
            ->addRegistrationId($reg_id)
            ->addIosNotification($txt,'default', '+1', true, '', array('id' => $question_id))
            ->build();
// 创建一个2016-12-22 13:45:00触发的定时任务
        $response = $client->schedule()->createSingleSchedule("定时任务", $payload, array("time"=>$time));


        $payload = $client->push()
            ->setPlatform("all")
            ->addRegistrationId($reg_id)
            ->addAndroidNotification($txt,'财税答疑', 1,  array('id' => $question_id))
            ->addIosNotification($txt,'default', '+1', true, '',  array('id' => $question_id))
            ->builds();
// 创建一个2016-12-22 13:45:00触发的定时任务
        $response = $client->schedule()->createSingleSchedule("定时任务", $payload, array("time"=>$time));

        $add = array(
            'reg_id' =>$reg_id,
            'content' =>$txt,
            'question_id' =>$question_id,
            'type' =>$type,
            'add_time' =>time(),
        );
        if($response->data->schedule_id){
            $add['status'] = 1;
            M('jpush_log')->add($add);
        }else{
            $add['status'] = 0;
            M('jpush_log')->add($add);
        }

    }
}